package org.yunai.swjg.server.module.player.template;

import org.jumpmind.symmetric.csv.CsvReader;
import org.yunai.swjg.server.core.constants.PlayerConstants;
import org.yunai.yfserver.util.CsvUtil;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * 升级经验模版
 * User: yunai
 * Date: 13-5-11
 * Time: 下午5:47
 */
public class LevelTemplate {

    /**
     * 等级
     */
    private Short level;
    /**
     * 所需经验
     */
    private Integer exp;

    public Short getLevel() {
        return level;
    }

    public Integer getExp() {
        return exp;
    }

    // ==================== 非set/get方法 ====================
    private static Map<Short, LevelTemplate> templates;

    public static void setTemplates(Map<Short, LevelTemplate> templates) {
        LevelTemplate.templates = templates;
        check();
    }

    public static LevelTemplate get(Short level) {
        return templates.get(level);
    }

    public static void load() {
        CsvReader reader = null;
        // 等级经验模版
        Map<Short, LevelTemplate> templates = new HashMap<>();
        try {
            reader = CsvUtil.createReader("csv/player/level_template.csv");
            reader.readHeaders();
            while (reader.readRecord()) {
                LevelTemplate template = genLevelTemplate(reader);
                templates.put(template.getLevel(), template);
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        } finally {
            if (reader != null) {
                reader.close();
            }
        }
        // 赋值
        LevelTemplate.setTemplates(templates);
    }

    private static LevelTemplate genLevelTemplate(CsvReader reader) throws IOException {
        LevelTemplate template = new LevelTemplate();
        template.level = CsvUtil.getShort(reader, "level", (short) 0);
        template.exp = CsvUtil.getInt(reader, "exp", 0);
        return template;
    }

    public static void check() {
        for (short i = 1; i < PlayerConstants.LEVEL_MAX; i++) {
            if (templates.get(i) == null) {
                throw new RuntimeException("等级：[" + i + "]的数据模版不存在！");
            }
        }
    }
}
